<template>
  <li :class="{ 'has-submenu': subItems && subItems.length }">
    <router-link
      :to="props.route"
      :class="{ active: isActive }"
      @click="handleClick"
      v-slot="{ navigate }"
    >
      <div @click="handleClick(navigate)">
        {{ props.title }}
      </div>
    </router-link>

    <ul v-if="props.subItems && subItems.length" class="submenu">
      <li v-for="(item, index) in subItems" :key="index">
        <router-link
          :to="item.route"
          :class="{ active: isSubActive(item.route) }"
        >
          {{ item.title }}
        </router-link>
      </li>
    </ul>
  </li>
</template>

<script setup>
import { computed } from "vue";
import { useRoute, useRouter } from "vue-router";

const props = defineProps({
  title: {
    type: String,
    required: true,
  },
  route: {
    type: String,
    default: "/",
  },
  subItems: {
    type: Array,
    default: () => [],
  },
});

const route = useRoute();
const router = useRouter();

// 判断当前菜单项是否激活
const isActive = computed(() => {
  if (props.route === "/") {
    return route.path === "/";
  }
  return route.path.startsWith(props.route);
});

// 判断子菜单项是否激活
const isSubActive = (itemRoute) => {
  return route.path === itemRoute;
};

// 处理一级菜单点击事件
const handleClick = (e) => {
  if (props.route === "/" || props.route === "/contact") {
    navigate(); // 手动跳转
  } else {
    // 阻止跳转
    event.preventDefault();
  }
};
</script>

<style scoped>
li {
  position: relative;
  flex: 1;
}

li > a {
  display: block;
  color: #fff;
  text-decoration: none;
  padding: 15px 20px;
  text-align: center;
  font-size: 16px;
}

li:hover > a {
  background-color: rgb(254, 0, 0);
}

/* 二级菜单样式 */
.submenu {
  position: absolute;
  top: 100%;
  left: 0;
  width: 100%;
  background-color: rgb(254, 0, 0);
  list-style: none;
  padding: 0;
  margin: 0;
  visibility: hidden;
  opacity: 0;
  transition: all 0.3s ease;
  transform: translateY(0);
  /* 移除向上偏移 */
  z-index: 1000;
  border-top: none;
  /* 移除顶部边框 */
}

.nav > li:hover .submenu {
  visibility: visible;
  opacity: 1;
  transform: translateY(0);
}

.submenu li {
  display: block;
  width: 100%;
  margin: 0;
  /* 移除外边距 */
}

.submenu li a {
  display: block;
  color: #fff;
  text-decoration: none;
  padding: 12px 20px;
  text-align: center;
  font-size: 14px;
  background-color: rgb(14, 34, 95);
  border: none;
  /* 移除边框 */
}

.submenu li:hover a {
  background-color: rgb(254, 0, 0);
}

/* 移除所有可能的间隙 */
.nav,
.submenu {
  font-size: 0;
  /* 移除内联元素间的空白 */
}

.nav > li,
.nav > li > a,
.submenu li,
.submenu li a {
  font-size: 14px;
  /* 恢复字体大小 */
}

/* 处理 router-link 的样式 */
a {
  text-decoration: none;
  color: inherit;
}

/* 添加激活状态的样式 */
.router-link-active,
a.active {
  background-color: rgb(254, 0, 0);
}

/* 子菜单激活状态样式 */
.submenu li a.active {
  background-color: rgb(254, 0, 0);
}
</style>
